#include "ModalFilterSystem.h"
#include "ModalFilter.h"
#include "PAInterface.h"

ModalFilterSystem::ModalFilterSystem(float minDuration, float maxDuration, float midFreq, float frequencyCeiling) :
	m_minDuration(minDuration), m_maxDuration(maxDuration), m_midFrequency(midFreq)
{
	//Calculate linear function coeffecients 
	float lowestFreq = 20;
	m_minDuration = minDuration;
	m_maxDuration = maxDuration;

	// y = mx + b

	float durationSpread = maxDuration - minDuration;
	m_upperFrequencyGradient = durationSpread / (frequencyCeiling - midFreq);
	m_lowerFrequencyGradient = -durationSpread / (midFreq - lowestFreq);

	m_lowerFreqYIntercept = m_maxDuration;
	//m_upperFreqYIntercept = minDuration - (m_lowerFrequencyGradient * midFreq);
	m_upperFreqYIntercept = 0.2;
}

float ModalFilterSystem::FrequencyDurationEnvelope(float frequency)
{
	//Calculate duration of sound based on it's frequency plotted against linear equations
	float duration;
	if( frequency >= m_midFrequency)
	{
		// y = mx + b
		duration = (m_upperFrequencyGradient * frequency) + m_upperFreqYIntercept;
	}
	else if( frequency < m_midFrequency)
	{
		// y = mx + b
		duration = (m_lowerFrequencyGradient * frequency) + m_lowerFreqYIntercept;
	}
	if (duration > m_maxDuration)
	{
		duration = m_maxDuration;
	}
	return duration;
}

void ModalFilterSystem::AddFilter(ModalFilter* filter)
{
	m_filters.push_back(filter);
}

void ModalFilterSystem::Process(float energy)
{

	int numFilters = m_filters.size();
	float divisor = 1.0f/(float)numFilters;
	int numSamples = int(m_maxDuration * SAMPLE_RATE);

	std::vector<float>* samples = new std::vector<float>;
	samples->reserve(numSamples);

	for(int j = 0; j < numSamples; j++)
	{
		float sample = 0;
		for(int i = 0 ; i < numFilters; i++)
		{
			//Iterate through filters, calculate its output and then sum the outputs in each frame
			sample += m_filters[i]->Process(j, energy, this);
		}
		//Scale amplitude
		sample *= divisor;
		samples->push_back(sample);

	}
	//Create temporary wave table
	ThePAInterface::Instance()->LoadTemporaryWaveTable(samples);
}